//
//  SelectPhotoTableViewCell.m
//  Rail
//
//  Created by hychen on 2018/3/17.
//  Copyright © 2018年 Hychen. All rights reserved.
//

#import "SelectPhotoTableViewCell.h"
#import "UIImage+DP.h"


@interface SelectPhotoTableViewCell ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) SelectPhotoView *photoView;
@property (nonatomic, strong) UIImagePickerController *imagePicker;
@property (nonatomic, strong) NSMutableArray *selectPhotoArray;
@end
@implementation SelectPhotoTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self setupSubviews];
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)setupSubviews {
    self.titleLabel = [UILabel labelWithText:@"" textColor:Color_RGB(44, 44, 44) font:[UIFont systemFontOfSize:18]];
    [self.contentView addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(self.contentView).offset(15);
        make.right.equalTo(self.contentView).offset(-15);
    }];
    
    self.photoView = [[SelectPhotoView alloc] init];
    self.photoView.maxSelectImageCount = 2;
    [self.contentView addSubview:self.photoView];
    [self.photoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.contentView);
        make.top.equalTo(self.titleLabel.mas_bottom).offset(15);
    }];
    BMWeakSelf
    [self.photoView setSelectPhotoBlock:^{
        [weakSelf showPhotoSelectorVc];
    }];
    
    [self.photoView setDeletePhotoBlock:^(id object) {
        [weakSelf deletePhotoWithModel:object];
    }];
    
    [self.photoView setEditPhotoBlock:^(id object) {
        
    }];
}

- (void)showPhotoSelectorVc {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusDenied) {
        //相册权限未开启
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        // app名称
        NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
        
        UIAlertView *alerView = [[UIAlertView alloc]initWithTitle:@"提醒" message:[NSString stringWithFormat:@"请在iPhone的“设置->隐私->照片”开启%@访问你的手机相册",app_Name] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerView show];
        return;
    }
    __weak typeof (self) weakSelf = self;
    SelectPhotoPictureViewController *vc = [[SelectPhotoPictureViewController alloc] init];
    vc.maxSelectImageCount = self.photoView.maxSelectImageCount - self.selectPhotoArray.count;
    vc.selectPhotoFinishBlock = ^(NSMutableArray *assetArray) {
        // 选中照片
        NSMutableArray *imageModelArray = [SelectPhotoTool getPostImageModelArrayWithAssetsArray:assetArray];
        [weakSelf.selectPhotoArray addObjectsFromArray:imageModelArray];
        // 更新选中相片布局
        weakSelf.photoView.selectedImageArray = weakSelf.selectPhotoArray;
        if (weakSelf.BlockSelectPhotoArray) {
            weakSelf.BlockSelectPhotoArray(weakSelf.selectPhotoArray);
        }
    };
    
    vc.takePictureCameraBlock = ^(){
        // 打开照相机
        [weakSelf openCameraPicker];
    };
    BaseNavigationController *navVc = [[BaseNavigationController alloc] initWithRootViewController:vc];
    [[BaseNavigationController rootNavigationController] presentViewController:navVc animated:YES completion:nil];
}

// 删除选中图片
- (void)deletePhotoWithModel:(SelectPhotoModel *)model
{
    // 移除选中图片数据
    [self.selectPhotoArray removeObject:model];
    
    // 更新选中相片布局
    self.photoView.selectedImageArray = self.selectPhotoArray;
    if (self.BlockSelectPhotoArray) {
        self.BlockSelectPhotoArray(self.selectPhotoArray);
    }
}

- (void)openCameraPicker {
    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                       message:@"你的设备没有相机!"
                                                      delegate:self
                                             cancelButtonTitle:nil
                                             otherButtonTitles:@"我知道了",
                              nil];
        [alert show];
    } else {
        if ([BMPhotoIOAuthTool checkCameraAuth]) {
            [[BaseNavigationController rootNavigationController] presentViewController:self.imagePicker animated:YES completion:nil];
        }
    }
}

// 拍摄完成
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
//    NSDictionary * imageMetadata = info[@"UIImagePickerControllerMediaMetadata"];
//    NSDictionary *tIFFDictionary =  [imageMetadata objectForKey:(NSString *)kCGImagePropertyTIFFDictionary];
//    NSString * pictureTime = tIFFDictionary[@"DateTime"];
    
    if ([mediaType isEqualToString:@"public.image"]){
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        SelectPhotoModel *model = [[SelectPhotoModel alloc] initWithImage:image imageDate:[NSDate date] uploadImage:[image zipImage]];
        [self.selectPhotoArray addObject:model];
        // 更新选中相片布局
        self.photoView.selectedImageArray = self.selectPhotoArray;
        if (self.BlockSelectPhotoArray) {
            self.BlockSelectPhotoArray(self.selectPhotoArray);
        }
    }
}

// 取消拍摄
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)setPhotoArray:(NSMutableArray *)selectPhotoArray {
    _selectPhotoArray = selectPhotoArray;
    self.photoView.selectedImageArray = selectPhotoArray;
}

- (NSMutableArray *)selectPhotoArray {
    if (!_selectPhotoArray) {
        _selectPhotoArray = [NSMutableArray array];
    }
    return _selectPhotoArray;
}

- (UIImagePickerController *)imagePicker
{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [_imagePicker setAllowsEditing:NO];
        _imagePicker.delegate = self;
    }
    return _imagePicker;
}

- (void)setTitle:(NSString *)title {
    _title = title;
    self.titleLabel.text = title;
}

- (void)setMaxCount:(NSInteger)maxCount {
    _maxCount = maxCount;
    self.photoView.maxSelectImageCount = maxCount;
}
@end
